package com.sxm.yiwei.activitis;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class RangingInMessageActivity extends BaseActivity implements View.OnClickListener {

    private ImageView rangmessageback;
    private EditText homeno;
    private EditText name;
    private EditText tellphone;
    private EditText address;
    private Button surebt;
    private String inhomeno;
    private String inname;
    private String tellphone1;
    private String inaddress;
    private List<GeocodeAddress> geocodeAddressList;
    private double latitude;

    private double longitude;
    private String id;
    private String consignorLat;
    private String consignorLong;
    private float distance;
    private SharedPreferences sharedPreferences;
    private String appId;
    private String userId;
    private String token;
    private String type;
    private String distwo;
    private String city;
    private String alatitude;
    private String alongitude;
    private String asnippet;
    private ImageView backmain;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ranging_in_message);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid", "0");
        userId = sharedPreferences.getString("userId", "1");
        token = sharedPreferences.getString("token", "2");
        city = sharedPreferences.getString("city", "");
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        consignorLat = intent.getStringExtra("consignorLat");
        consignorLong = intent.getStringExtra("consignorLong");
        initRangMessageView();
    }

    private void initRangMessageView() {
        backmain = (ImageView) findViewById(R.id.ranginginmsg_backmain);
        rangmessageback = (ImageView) findViewById(R.id.rangingmessage_back);
        homeno = (EditText) findViewById(R.id.rangmessage_homeno);
        name = (EditText) findViewById(R.id.rangmessage_name);
        tellphone = (EditText) findViewById(R.id.rangmessage_tellphone);
        address = (EditText) findViewById(R.id.rangmessage_address);
        surebt = (Button) findViewById(R.id.rangmessage_surebt);
        rangmessageback.setOnClickListener(this);
        surebt.setOnClickListener(this);
        address.setOnClickListener(this);
        backmain.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ranginginmsg_backmain:
                startActivity(new Intent(RangingInMessageActivity.this,MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;
            case R.id.rangingmessage_back:
                finish();
                break;
            case R.id.rangmessage_surebt:
                String text = String.valueOf(address.getText());
                if (text.equals("")){
                    Toast.makeText(this, "请填写地址信息", Toast.LENGTH_SHORT).show();
                }else {
                    getDistance(Double.valueOf(alatitude),Double.valueOf(alongitude));
                }

                break;
            case R.id.rangmessage_address:
                Intent intent = new Intent(RangingInMessageActivity.this,InPOISearchActivity.class);
                startActivityForResult(intent,11);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (data==null){

        }else {
            if (resultCode==10){
                alatitude = data.getStringExtra("latitude");
                alongitude = data.getStringExtra("longitude");
                asnippet = data.getStringExtra("snippet");
                address.setText(asnippet);

            }
        }
    }
    /**
     * 获取两点之间的距离 (已知位置和目标位置)
     * @param latitude 目标位置的纬度
     * @param longitude 目标位置的经度
     */
    private void getDistance(final double latitude, final double longitude) {
        inname = String.valueOf(name.getText());
        tellphone1 = String.valueOf(tellphone.getText());
        inhomeno = String.valueOf(homeno.getText());
        RouteSearch search = new RouteSearch(RangingInMessageActivity.this);

        LatLonPoint slat = new LatLonPoint(Double.valueOf(consignorLat),Double.valueOf(consignorLong));// 起点
        final LatLonPoint elat = new LatLonPoint(latitude,longitude);// 终点
        RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(slat,elat);
        RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo,RouteSearch.DrivingShortDistance,null,null,"");
        search.calculateDriveRouteAsyn(query);
        search.setRouteSearchListener(new RouteSearch.OnRouteSearchListener() {
            @Override
            public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

            }

            @Override
            public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {
                // 拿结果
                List<DrivePath> paths = driveRouteResult.getPaths();
                for (int i1 = 0; i1 < paths.size(); i1++) {


                    distance = paths.get(i1).getDistance();

                    distwo = String.valueOf(new BigDecimal(distance).divide(new BigDecimal(1), 2, BigDecimal.ROUND_FLOOR));

                }
                RequestParams params = new RequestParams(InternetAddressUtis.Url + InternetAddressUtis.ADDADDRESS);
                params.addHeader("Content-Type", "application/json");
                params.addHeader("token", token);
                params.addHeader("appId", appId);
                params.addHeader("userId", userId);
                JSONObject j = new JSONObject();
                j.put("orderId",id);
                j.put("address",asnippet);
                j.put("longitude",String.valueOf(longitude));
                j.put("latitude",String.valueOf(latitude));
                j.put("distance",String.valueOf(Double.valueOf(distwo)/1000));
                j.put("name",inname);
                j.put("telephone",tellphone1);
                j.put("houseNumber",inhomeno);
                params.setBodyContent(j.toJSONString());

                x.http().post(params, new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        Intent i = new Intent(RangingInMessageActivity.this,RangingResultActivity.class);
                        i.putExtra("id",id);
                        i.putExtra("distance",String.valueOf(distance));
                        i.putExtra("tellphone1",tellphone1);
                        i.putExtra("inname",inname);
                        i.putExtra("inaddress",inaddress);

                        startActivity(i);
                        finish();
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        ErrType.errType(RangingInMessageActivity.this,ex);
                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });

            }

            @Override
            public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

            }

            @Override
            public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

            }
        });

    }
}
